import React, { createContext, useContext, useState, useCallback } from 'react';
import type { ReactNode } from 'react';
import axios from 'axios';

// 统计数据类型定义
interface UserStats {
    user_counts: {
        total: number;
        active: number;
        inactive: number;
        staff: number;
        superuser: number;
    };
    feature_usage: {
        with_face_data: number;
        without_face_data: number;
        with_nfc_card: number;
        without_nfc_card: number;
    };
    registration_trends: {
        new_today: number;
        new_this_week: number;
        new_this_month: number;
    };
    activity_trends: {
        active_today: number;
        active_this_week: number;
        active_this_month: number;
    };
}

// Context类型定义
interface AdminStatsContextType {
    stats: UserStats | null;
    loading: boolean;
    error: string | null;
    refreshStats: () => Promise<void>;
    updateStatsAfterUserOperation: () => Promise<void>;
}

// 创建Context
const AdminStatsContext = createContext<AdminStatsContextType | undefined>(undefined);

// Provider组件属性
interface AdminStatsProviderProps {
    children: ReactNode;
}

// Provider组件
export const AdminStatsProvider: React.FC<AdminStatsProviderProps> = ({ children }) => {
    const [stats, setStats] = useState<UserStats | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // 获取统计数据的函数
    const fetchStats = useCallback(async (): Promise<UserStats | null> => {
        const token = localStorage.getItem('adminAuthToken');
        if (!token) {
            setError('未找到管理员认证令牌');
            return null;
        }

        try {
            const response = await axios.get('/api/admin/users/stats/', {
                headers: { 'Authorization': `Token ${token}` }
            });
            return response.data;
        } catch (err: any) {
            console.error('Failed to fetch stats:', err);
            setError(err.response?.data?.message || '获取统计数据失败');
            return null;
        }
    }, []);

    // 刷新统计数据
    const refreshStats = useCallback(async () => {
        setLoading(true);
        setError(null);
        
        try {
            const newStats = await fetchStats();
            if (newStats) {
                setStats(newStats);
            }
        } finally {
            setLoading(false);
        }
    }, [fetchStats]);

    // 用户操作后更新统计数据（静默更新，不显示loading）
    const updateStatsAfterUserOperation = useCallback(async () => {
        try {
            const newStats = await fetchStats();
            if (newStats) {
                setStats(newStats);
            }
        } catch (err) {
            // 静默失败，不影响用户体验
            console.warn('Failed to update stats after user operation:', err);
        }
    }, [fetchStats]);

    const value: AdminStatsContextType = {
        stats,
        loading,
        error,
        refreshStats,
        updateStatsAfterUserOperation,
    };

    return (
        <AdminStatsContext.Provider value={value}>
            {children}
        </AdminStatsContext.Provider>
    );
};

// 自定义Hook
export const useAdminStats = (): AdminStatsContextType => {
    const context = useContext(AdminStatsContext);
    if (context === undefined) {
        throw new Error('useAdminStats must be used within an AdminStatsProvider');
    }
    return context;
};

// 导出Context（用于高级用法）
export { AdminStatsContext };
